package com.zkc.blog.controller.admin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zkc.blog.pojo.User;
import com.zkc.blog.service.UserService;
import com.zkc.blog.uilt.ResultEntity;

@RestController
public class UserController {

	@Autowired
	private UserService userService;
	
	//增
	@PostMapping("/user")
	public ResultEntity<String> addUser(
			@RequestBody User user
			){
		try {
			userService.insertUser(user);
		} catch (Exception e) {
			return ResultEntity.failed(e.getMessage());
		}
		return ResultEntity.successWithoutData();
	}
	//删
	@DeleteMapping("/user")
	public ResultEntity<String> deleteUsers(
			@RequestBody List<Integer> userids
			){
		try {
			userService.deleteUserByIds(userids);
		} catch (Exception e) {
			return ResultEntity.failed(e.getMessage());
		}
		return ResultEntity.successWithoutData();
	}
	//查
	@GetMapping("/user")
	public ResultEntity<PageInfo<User>> getUsers(
			@RequestParam(value = "searchkey", defaultValue = "") String  searchkey,
			@RequestParam(value = "start", defaultValue = "0") int start,
			@RequestParam(value = "size", defaultValue = "5") int size){
		PageHelper.startPage(start,size,"userid desc");//这句要先启动
		List<User> list=userService.getUserList(searchkey);
		PageInfo<User> page = new PageInfo<>(list);//分页处理
		
		return ResultEntity.successWithoutData(page);
	}
	//查
	@GetMapping("/user/{id}")
	public ResultEntity<User> getUserById(
			@PathVariable("id") Integer  id){
		try {
			User u=userService.getUserById(id);
			return ResultEntity.successWithoutData(u);
		} catch (Exception e) {
			return ResultEntity.failed(e.getMessage());
		}
	}
	//改
	@PutMapping("/user")
	public ResultEntity<String> updateUser(
			@RequestBody User user
			){
		try {
			userService.updateUser(user);
		} catch (Exception e) {
			return ResultEntity.failed(e.getMessage());
		}
		return ResultEntity.successWithoutData();
	}
}
